﻿#include "com_manager.h"
#include "dialog_nuf_bus_setting.h"
#include "label_net.h"
#include "plug_info.h"
#include "com_rs232.h"


#include <QMessageBox>
#include <QMouseEvent>
#include <nuf_bus_info.h>
#include <mhelper.h>
#include "dialog_ethernet_setting.h"

#pragma execution_character_set("utf-8")


LabelNet::LabelNet(QWidget* parent) : QLabel(parent) {
	this->setAlignment(Qt::AlignHCenter);
}


// 重写鼠标点击事件 mousePressEvent()
void LabelNet::mousePressEvent(QMouseEvent* event)
{
	//Qt::LeftButton
	//Qt::RightButton
	if (event->button() == Qt::LeftButton)
	{
		//QMessageBox::information(NULL, "单击", "单击了我" + this->text(), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
	//	DialogEthernetSetting dlg(this->toolTip());
	//	dlg.exec();
	}
}

// 重写鼠标事件处理 event()
bool LabelNet::event(QEvent* e)
{
	if (e->type() == QEvent::MouseButtonDblClick)
	{
		QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(e);
		if (mouseEvent->button() == Qt::LeftButton)
		{
			QString s = this->objectName();
			int pos_1 = s.lastIndexOf('_');
			int p = s.mid(pos_1 + 1).toInt();

			QString b = this->parent()->objectName();

			int pos_2 = b.lastIndexOf('_');
			int board = b.mid(pos_2 + 1).toInt();

			if (board < 1 || board > 12)
			{
				return false;
			}

            QString comName= NufBusSetting::map_bus[board - 1].port_name.toUpper();
            rs232com* rs232 = com_manager::instance()->get_com(comName );
            if (rs232 ==nullptr)
            {
                mHelper::ShowMessageBoxInfo(QString("%1不存在！").arg(comName));
                DialogNufBusSetting boardDlg;
                boardDlg.exec();
            }
            // bool opened=  rs232.openPort( NodeSetting::map_bus[board-1].port_name, BaudRateType::BAUD115200 , DataBitsType::DATA_8 ,  ParityType::PAR_NONE , StopBitsType::STOP_1 );
            else
			{
                // TODO: ???????????????????
                TOPO_NODE*node=	rs232->query_current_node_info();
                QString mac_id = rs232->query_mac_address();
                node-> mac_id=mac_id;
                node->comName = comName;


				int e_id = s.mid(11).toInt();

				QString node_ = QString("ethernet_%1").arg(e_id, 2, 10, QLatin1Char('0'));
                
                PlugInfo::map_ethernet[node_].ip = rs232->mac_id.mid(3, 11);

                NufBusSetting::map_bus[board - 1].mac_id = rs232->mac_id;

				DialogEthernetSetting dlg(p, board);

				dlg.exec();


                TopoInfo::Instance()->save_topo_setting();
                NufBusSetting::save_Bus_Setting() ;
                PlugInfo::save_port_Setting() ;

				return true;
			}
		}
	}
	return QLabel::event(e);
}
